package com.cristina.attention.interceptor;

import com.cristina.attention.utils.RequestHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author by superman
 */
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    /**
     * feign 调用之前进行拦截
     * 获取用户的 token, 再将 token 封装到请求头中传递到下一个微服务中
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = RequestHolder.currentRequestAttributes();
        if (Objects.isNull(request)) {
            return ;
        }
        Map<String, String> headers = getHeaders(request);
        if (headers.size() < 1) {
            return ;
        }
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            template.header(entry.getKey(), entry.getValue());
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest req) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enums = req.getHeaderNames();
        while (enums.hasMoreElements()) {
            String key = enums.nextElement();
            String value = req.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

}
